package com.pickup.controller;

import com.pickup.netty.enums.NettyResultType;
import com.pickup.netty.message.NettyData;
import com.pickup.netty.server.handler.ChatInboundHandler;
import com.pickup.netty.server.session.Session;
import com.pickup.netty.server.session.SessionFactory;
import com.pickup.pojo.*;
import com.pickup.req.bo.UserContactListBo;
import com.pickup.resp.JSONResult;
import com.pickup.resp.MomentsVo;
import com.pickup.utils.FastDFSClient;
import com.pickup.utils.JsonUtils;
import com.pickup.utils.SidUtil;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletRequest;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("f")
public class FileController {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private SidUtil sidUtil;

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping("singleUpload")
    public String singleUpload(ServletRequest request) throws Exception {
        MultipartHttpServletRequest fRequest = (MultipartHttpServletRequest) request;
        Iterator<String> files = fRequest.getFileNames();
        while (files.hasNext()){
            MultipartFile file = fRequest.getFile(files.next());
            if (file!=null){
                return fastDFSClient.uploadFile(file);
            }
        }
        return null;
    }

    @PostMapping("multipleUpload")
    public String multipleUpload(ServletRequest request) throws Exception {
        MultipartHttpServletRequest fRequest = (MultipartHttpServletRequest) request;
        Iterator<String> files = fRequest.getFileNames();
        StringBuilder ImgList = new StringBuilder();
        while (files.hasNext()){
            MultipartFile file = fRequest.getFile(files.next());
            if (file!=null){
                ImgList.append(fastDFSClient.uploadFile(file)).append(",");
            }
        }
        return ImgList.toString();
    }

    @PostMapping("addMoments")
    public JSONResult addMoments(@RequestBody Moments moments) throws Exception {
        ChannelGroup users = ChatInboundHandler.users;
        for (UserContactListBo userContactListBo : moments.getContactList()) {
            String friendUserId = userContactListBo.getFriendUserId();
            Channel channel = SessionFactory.getSession().getChannel(friendUserId);
            System.out.println(channel);
            if (channel != null && users.find(channel.id()) != null) {
                NettyData nettyData = new NettyData();
                nettyData.setAction(NettyResultType.AcceptMoments);
                channel.writeAndFlush(new TextWebSocketFrame(JsonUtils.objectToJson(nettyData)));
            }
        }
        moments.setCreateTime(new Date().getTime());
        moments.setId(sidUtil.nextShort());
        mongoTemplate.save(moments);
        return JSONResult.build(200,"发布成功!", moments);
    }

    @PostMapping("findMoments")
    public JSONResult findMoments(@RequestBody List<UserContactListBo> users) throws Exception {
        List<ThumbsUp> thumbsUp = null;
        List<Comment> comments = null;

        ArrayList<String> arrayList = new ArrayList<>();
        for (UserContactListBo user : users) {
            arrayList.add(user.getFriendUserId());
        }
        Query queryMoments = new Query(Criteria.where("userId").in(arrayList));
        List<Moments> momentsList = mongoTemplate.find(queryMoments, Moments.class);
        momentsList.sort(Comparator.comparing(Moments::getCreateTime).reversed());

        List<MomentsVo> momentsVos = new ArrayList<>();

        for (Moments moments : momentsList) {

            MomentsVo momentsVo = new MomentsVo();
            BeanUtils.copyProperties(moments, momentsVo);

            Query queryTh = new Query(Criteria.where("momentId").is(moments.getId()));
            Query queryCo = new Query(Criteria.where("momentId").is(moments.getId()));
            thumbsUp = mongoTemplate.find(queryTh, ThumbsUp.class);
            comments = mongoTemplate.find(queryCo, Comment.class);
            momentsVo.setComments(comments);
            momentsVo.setThumbsUps(thumbsUp);
            momentsVos.add(momentsVo);
        }

        return JSONResult.build(200,"", momentsVos);
    }


    @PostMapping("thumbsUp")
    public JSONResult thumbsUp(@RequestBody ThumbsUp thumbsUp) throws Exception {
        thumbsUp.setId(sidUtil.nextShort());

        Query queryTh = new Query(Criteria.where("momentId").is(thumbsUp.getMomentId())
                .and("thumbsUpUserId").is(thumbsUp.getThumbsUpUserId()));
        List<ThumbsUp> thumbsUps = mongoTemplate.find(queryTh, ThumbsUp.class);
        if (thumbsUps.size() > 0){
            mongoTemplate.remove(queryTh, ThumbsUp.class);
        }
        mongoTemplate.save(thumbsUp);
        return JSONResult.build(200,"", thumbsUp);
    }

    @PostMapping("reply")
    public JSONResult reply(@RequestBody Comment comment) throws Exception {
        mongoTemplate.save(comment);
        return JSONResult.build(200,"1111111111111", comment);
    }

}
